<template>
  <!-- 单曲夹 -->
  <div
    class="m-singleDir-detail"
    v-title
    :data-title="$t('router.singleTitle')"
  >
    <div class="main">
      <div class="top-box">
        <div class="album-info">
          <div class="image">
            <el-image
              :src="info.imgUrl"
              fit="fill"
              :preview-src-list="[info.imgUrl]"
            >
              <div
                slot="placeholder"
                class="image-slot flex-center flex-column"
              >
                <i class="iconfont el-icon-loading"></i>
                <p>
                  {{ $t("public.loading") }}
                  <span class="dot">...</span>
                </p>
              </div>
              <div slot="error" class="image-slot flex-center">
                <img src="@/assets/images/defaultCover.png" />
              </div>
            </el-image>
          </div>
          <div class="info">
            <div class="title">
              <div class="editTitle" v-if="inputVisible">
                <el-input
                  class="input-new-tag"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="mini"
                  maxlength="20"
                  show-word-limit
                >
                </el-input>
                <el-button type="text" @click="handleInputConfirm">{{
                  $t("public.save")
                }}</el-button>
                <el-button type="text" @click.native="inputVisible = false">{{
                  $t("public.cancel")
                }}</el-button>
              </div>
              <div v-else>
                <h2 v-text="info.name" contenteditable="true"></h2>
                <i class="el-icon-edit" @click="showInput"></i>
              </div>
            </div>
            <li class="info-text">
              <span>{{ $t("public.createTime") }}：</span
              >{{ utils.formateDate(info.createTime) }}
            </li>
            <li>
              <el-button
                type="text"
                v-if="info.dirId == playClipId && playClipId != null && playing"
                class="icon-button"
                size="small"
                @click="play('pauseAll')"
                ><svg-icon name="pause" class="icon icon-pause" />{{
                  $t("public.pause")
                }}</el-button
              >
              <el-button
                v-else
                type="text"
                class="icon-button"
                size="small"
                @click="play('playAll')"
                ><svg-icon name="play" class="icon icon-play" />{{
                  $t("public.playAll")
                }}</el-button
              >
            </li>
          </div>
        </div>
        <div class="top-btn">
          <el-button
            type="text"
            class="icon-button"
            size="small"
            @click="openConfirm('playList')"
            ><svg-icon name="play-list" class="icon icon-play-list" />{{
              $t("public.addToPlaylist")
            }}</el-button
          >
          <el-button
            type="text"
            class="icon-button"
            @click="openDialog('addSingles')"
            size="small"
            ><svg-icon name="add" class="icon icon-add" />{{
              $t("main.addToSingleClip")
            }}</el-button
          >
          <el-button
            type="text"
            @click="openConfirm('deleteDir')"
            icon="el-icon-delete-solid"
            size="small"
            >{{ $t("public.deleteClip") }}</el-button
          >
        </div>
      </div>
      <div class="table-box">
        <el-table
          ref="songListTable"
          class="singleTable"
          :data="tableData"
          highlight-current-row
          @selection-change="handleSelectionChange"
          v-loading="fullscreenLoading"
          v-el-table-infinite-scroll="load"
          infinite-scroll-disabled="isPage"
          infinite-scroll-delay="120"
          infinite-scroll-immediate="false"
          size="mini"
          height="100%"
        >
          <el-table-column type="selection"> </el-table-column>
          <el-table-column
            :label="$t('main.NOSingleName')"
            min-width="80%"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div
                class="singName ellipsis"
                :class="
                  currentSong.trackId == scope.row.trackId && playing
                    ? 'playing'
                    : ''
                "
                @click="play('songList', scope.row)"
              >
                <span class="row-index">
                  <span class="playIndex">{{ scope.$index + 1 }}</span>
                  <img
                    src="@/assets/images/playGif.gif"
                    class="playGif pointer"
                  />
                  <svg-icon name="pause" class="icon icon-pause" />
                </span>
                <!-- <svg-icon name="play" class="icon playGif"/> -->
                <span
                  v-text="
                    $i18n.locale === 'zh'
                      ? scope.row.trackCtitle || scope.row.trackTitle
                      : scope.row.trackTitle
                  "
                ></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column min-width="20">
            <template #header>
              <span
                @click="openConfirm('removeDirChilds')"
                class="icon el-icon-delete-solid"
              ></span>
            </template>
            <template slot-scope="scope">
              <span
                @click="openConfirm('removeDirChild', scope.row.trackId)"
                class="icon el-icon-delete-solid"
              ></span>
            </template>
          </el-table-column>
          <p class="el-icon-loading"></p>
        </el-table>
      </div>
    </div>
    <div class="page-wrap" v-show="isPage">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNum"
        :page-size="params.pageSize"
        background
        hide-on-single-page
        layout="total, prev, pager, next, jumper"
        :total="total"
        small
      >
      </el-pagination>
    </div>

    <!--弹窗界面-->
    <el-dialog
      width="20%"
      :title="$t(textMap[dialogStatus])"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <!-- 添加到单曲夹 -->
      <el-form
        v-if="this.dialogStatus == 'addSingles'"
        :model="addSingles"
        class="addSingles"
        :rules="rules"
        ref="addSingles"
      >
        <el-form-item prop="select">
          <el-select
            v-model="addSingles.select"
            clearable
            filterable
            :placeholder="$t('public.selectSingles')"
          >
            <el-option
              v-for="item in options"
              :key="item.dirId"
              :label="item.name"
              :value="item.dirId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="addSingles.select === '0'"
          :label="$t('public.newSingles')"
          prop="name"
        >
          <el-input
            class="input-new-tag"
            v-model="addSingles.name"
            maxlength="20"
            show-word-limit
            :placeholder="$t('main.enterSingleName')"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="clearBtn" @click.native="dialogFormVisible = false">{{
          $t("public.cancel")
        }}</el-button>
        <el-button type="primary" @click="createData(dialogStatus)">{{
          $t("public.save")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import drawerList from "@/components/common/drawerList/Index";
import { mapMutations, mapGetters, mapActions } from "vuex";
import elTableInfiniteScroll from "el-table-infinite-scroll";
export default {
  directives: {
    "el-table-infinite-scroll": elTableInfiniteScroll,
  },
  data() {
    return {
      tableData: [],
      fullscreenLoading: false,
      multipleSelection: [], //多选
      activeTrackId: -1, // 单曲ID 展开workName
      // 当前选中行
      currentRow: null,
      // el-dialog相关
      textMap: {
        // 添加与编辑界面
        addSingles: "main.addToSingleClip",
      },
      options: [], //单曲夹下拉
      dialogFormVisible: false, //弹窗
      dialogStatus: "", //编辑框界面切换
      // 添加单曲夹弹窗信息
      addSingles: {
        select: "",
        name: "",
      },
      params: {
        type: 2,
        // 1.唱片夹,2.单曲夹
        pageSize: 30,
        // 当前页数
        pageNum: 1,
        // code: "",
      },
      isPage: false, //显示加载更多或分页
      total: 0, //总条数
      info: {}, //当前文件夹top展示信息
      inputValue: "", //编辑标题展示字段
      inputVisible: false,
    };
  },
  components: {
    // drawerList,
  },
  computed: {
    ...mapGetters([
      "loginStatu",
      "playing",
      "playLists",
      "currentSong",
      "playClipId",
    ]),
    rules() {
      return {
        select: [
          {
            required: true,
            message: this.$t("public.selectSingles"),
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: this.$t("public.SinglesCannotEmpty"),
            trigger: "blur",
          },
        ],
      };
    },
  },
  watch: {},
  created() {},
  mounted() {
    this.getSongSheetDir();
  },
  methods: {
    ...mapMutations({
      setPlayList: "SET_PLAYLIST",
      setPlayParentId: "SET_PLAY_PARENT_ID",
      setPlayClipId: "SET_PLAY_CLIP_ID",
    }),
    ...mapActions([
      // 点击选择播放
      "selectPlay",
      // 点击播放全部
      "playAll",
      "playStatus",
      "savePlayList",
      "clearPlayList",
    ]),
    //分页 每页条数
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getDirChildContent();
    },
    //当前页
    handleCurrentChange(val) {
      this.params.pageNum = val;
      this.tableData = [];
      this.getDirChildContent();
    },
    //获取文件夹
    async getSongSheetDir() {
      try {
        let param = {
          type: 2,
          pageNum: this.$route.params.pageNum,
          pageSize: this.$route.params.pageSize,
        };
        let res = await this.$api.user.getDirList(param);
        if (res.code === 1000000 && res.source.length > 0) {
          this.info = res.source.find((x) => x.dirId == this.$route.params.id);
          this.getDirChildContent();
        } else if (res.code === 1000000 && res.source.length == 0) {
          this.info = {};
          this.tableData = [];
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取单曲夹下内容
    async getDirChildContent() {
      this.fullscreenLoading = true;
      try {
        let params = Object.assign({ dirId: this.info.dirId }, this.params);
        let res = await this.$api.user.getDirChildContent(params);
        if (res.code === 1000000) {
          this.tableData = res.source ? res.source : [];
          this.total = res.total;
          this.fullscreenLoading = false;
          if (res.size < 50 && res.size < res.total) {
            this.loading = true;
            this.isPage = false;
          } else {
            this.loading = false;
            this.isPage = true;
          }
        } else {
          this.fullscreenLoading = false;
          this.tableData = [];
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 打开弹窗界面
    async openDialog(type) {
      if (!this.loginStatu) {
        this.$notify.error({
          title: this.$t("public.sorry"),
          message: this.$t("public.loginPermission"),
          duration: 1500,
        });
        return;
      }
      this.dialogStatus = type;
      let res;
      if (type == "addSingles") {
        if (this.multipleSelection.length > 0) {
          res = await this.$api.user.getDirList(this.params);
          if (res.code === 1000000) {
            this.options = res.source;
            this.options.unshift({
              name: this.$t("public.newSingles"),
              dirId: "0",
            });
          }
          this.dialogFormVisible = true;
        } else {
          this.$message({
            showClose: true,
            message: this.$t("public.selectAddSingle"),
            type: "warning",
            duration: 1000,
          });
          return;
        }
      }
      this.$nextTick(() => {
        this.$refs[type].resetFields();
      });
    },
    //弹窗 提交按钮
    createData(type) {
      this.$refs[type].validate(async (valid) => {
        if (valid) {
          if (type == "addSingles") {
            //单曲夹
            let params;
            if (this.addSingles.select === "0") {
              let param = {
                name: this.addSingles.name,
                type: 2,
              };
              let res = await this.$api.user.addDir(param);
              if (res.code === 1000000) {
                params = {
                  userDirChildAdds: this.multipleSelection.map((item) => {
                    return Object.assign(
                      {},
                      { contentId: item.trackId },
                      { moduleId: item.musicAlbum.moduleId || "" }
                    );
                  }),
                  dirId: res.source,
                  type: 2,
                };
              } else if (res.code === 1700401) {
                this.$message({
                  showClose: true,
                  message: this.$t("public.singleExists"),
                  type: "error",
                });
              }
            } else {
              params = {
                userDirChildAdds: this.multipleSelection.map((item) => {
                  return Object.assign(
                    {},
                    { contentId: item.trackId },
                    { moduleId: item.musicAlbum.moduleId || "" }
                  );
                }),
                dirId: this.addSingles.select,
                type: 2,
              };
            }
            let res = await this.$api.user.addDirChild(params);
            if (res.code === 1000000) {
              this.$message({
                showClose: true,
                message: this.$t("public.addSuccess"),
                type: "success",
                duration: 1000,
              });
              this.getSongSheetDir();
              this.dialogFormVisible = false;
            }
          }
        }
      });
    },
    // Confirm弹框
    openConfirm(type, trackId) {
      if (!this.loginStatu) {
        this.$notify.error({
          title: this.$t("public.sorry"),
          message: this.$t("public.loginPermission"),
          duration: 1500,
        });
        return;
      }
      if (type == "playList" && this.multipleSelection == 0) {
        this.$message({
          showClose: true,
          message: this.$t("public.selectAddSingle"),
          type: "warning",
          duration: 1000,
        });
        return;
      } else if (type == "removeDirChilds" && this.multipleSelection == 0) {
        this.$message({
          showClose: true,
          message: this.$t("public.selectDeleteSingle"),
          type: "warning",
          duration: 1000,
        });
        return;
      }
      let text = "";
      if (type == "deleteDir") {
        text = this.$t("main.sureDeleteSingleClip");
      } else if (type == "playList") {
        text = this.$t("public.sureToAddToPlaylist");
      } else if (type == "removeDirChild") {
        text = this.$t("public.deleteCurrentSingle");
      } else if (type == "removeDirChilds") {
        text = this.$t("public.deleteSelectSingle");
      }
      this.$confirm(text, {
        confirmButtonText: this.$t("public.confirm"),
        cancelButtonText: this.$t("public.cancel"),
        // type: "warning",
        showClose: false,
        center: true,
      })
        .then(async () => {
          let id = this.info.dirId;
          if (type == "playList") {
            // this.utils.addArrItem(this.multipleSelection,{albumName: this.list.name},{albumCname: this.list.cname || this.list.name,})
            this.savePlayList({
              list: this.multipleSelection,
              location: "end",
            });
            this.$message({
              showClose: true,
              message: this.$t("public.singleAddedPlaylist"),
              type: "success",
              duration: 1000,
            });
          } else if (type == "deleteDir") {
            await this.$api.user.deleteDir({ dirId: id });
            this.$router.push({ name: "mMyMusicSingleDir" });
            this.$message({
              showClose: true,
              message: this.$t("public.successfullyDelete"),
              type: "success",
              duration: 1000,
            });
          } else if (type == "removeDirChild") {
            if (this.currentSong.trackId === trackId) {
              this.$message({
                message: this.$t("public.cannotDeleteCurrentlyPlaying"),
                offset: 46,
                type: "warning",
                duration: 1000,
                showClose: true,
              });
              return false;
              // this.selectPlay({
              //   list: [],
              //   index: "0",
              // });
            }
            let params = {
              dirId: id,
              contentIds: [trackId],
              selectState: 2, //未全选
            };
            await this.$api.user.removeDirChild(params);
            this.$message({
              showClose: true,
              message: this.$t("public.successfullyDelete"),
              type: "success",
              duration: 1000,
            });
          } else if (type == "removeDirChilds") {
            // 播放列表包含 当前播放歌曲
            let idx;
            const flag = this.multipleSelection.some((item, index) => {
              if (item.trackId === this.currentSong.trackId) {
                idx = index;
                return true;
              }
            });
            // 包含并播放状态 -不清空
            if (flag && this.playing) {
              if (this.multipleSelection.length == 1) {
                this.$message({
                  message: this.$t("public.cannotDeleteCurrentlyPlaying"),
                  offset: 46,
                  type: "warning",
                  duration: 1500,
                  showClose: true,
                });
                return false;
              }
              this.multipleSelection.splice(idx, 1);
              // 设置播放列表为当前播放歌曲(循环播放)
              this.selectPlay({
                list: [this.currentSong],
                index: this.currentSong.trackId,
              });
            } else if (flag) {
              this.selectPlay({
                list: [],
                index: "0",
              });
            }
            let params = {
              dirId: id,
              contentIds: this.multipleSelection.map((item) => {
                return item.trackId;
              }),
              selectState:
                this.multipleSelection.length === this.tableData.length ? 1 : 2,
            };
            await this.$api.user.removeDirChild(params);
            this.$message({
              showClose: true,
              message: this.$t("public.successfullyDelete"),
              type: "success",
              duration: 1000,
            });
          }
          this.getSongSheetDir();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //播放
    async play(type, item) {
      if (!this.loginStatu) {
        this.$notify.error({
          title: this.$t("public.sorry"),
          message: this.$t("public.loginPermission"),
          duration: 1500,
        });
        return;
      } else if (this.tableData.length == 0) {
        this.$message({
          showClose: true,
          message: this.$t("public.noSingleToPlay"),
          type: "warning",
          duration: 1000,
        });
        return;
      }
      if (type == "playAll") {
        this.setPlayClipId(this.info.dirId);
        this.setPlayParentId(null);
        if (this.multipleSelection.length > 0) {
          this.savePlayList({
            list: this.multipleSelection,
            location: "start",
          });
          this.selectPlay({
            list: this.playLists,
            index: this.multipleSelection[0].trackId,
          });
          this.$refs.songListTable.clearSelection();
        } else {
          // 添加到播放列表
          this.savePlayList({ list: this.tableData, location: "start" });
          this.playAll({
            list: this.playLists,
          });
        }
      } else if (type == "songList") {
        if (this.currentSong.trackId == item.trackId && this.playing) {
          this.playStatus(false);
        } else {
          this.setPlayClipId(this.info.dirId);
          this.setPlayParentId(null);
          this.savePlayList({ list: this.tableData, location: "start" });
          this.selectPlay({
            list: this.playLists,
            index: item.trackId,
          });
        }
      } else if (type == "pauseAll") {
        this.playStatus(false);
      }
    },
    // 加载更多
    load() {
      this.params.pageSize += 20;
      this.getDirChildContent();
    },
    openWorkName(idx) {
      if (idx == this.activeTrackId) {
        this.activeTrackId = -1;
      } else {
        this.activeTrackId = idx;
      }
      // this.isWorkName = !this.isWorkName;
    },
    //多选事件
    handleSelectionChange(val) {
      // this.isIndeterminate =
      //   checkedCount > 0 && checkedCount < this.tableData.length;
      this.multipleSelection = val;
    },
    // 编辑标题
    showInput() {
      this.inputValue = this.info.name;
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    async handleInputConfirm() {
      if (this.inputValue.trim() === "") {
        this.$message({
          showClose: true,
          message: this.$t("public.SinglesCannotEmpty"),
          type: "error",
          duration: 1000,
        });
      } else if (this.inputValue === this.info.name) {
        this.inputVisible = false;
      } else {
        let params = {
          dirId: this.info.dirId,
          name: this.inputValue,
          type: 2,
        };
        let res = await this.$api.user.updateDirName(params);
        if (res.code === 1000000) {
          this.info.name = this.inputValue;
          this.inputVisible = false;
        } else if (res.code === 1700401) {
          this.$message({
            showClose: true,
            message: this.$t("public.singleExists"),
            type: "error",
            duration: 1000,
          });
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.m-singleDir-detail {
  .main {
    width: 100%;
    // min-height: 580px;
    // display: flex;
    // flex-direction: column;
    .top-box {
      height: 160px;
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin: 10px 0;
      .el-button {
        font-size: 14px;
        font-weight: 500;
      }
      .album-info {
        display: flex;
        .el-image {
          width: 120px;
          height: 120px;
          display: flex;
          align-items: center;
          justify-content: center;
          img {
            width: 100%;
            height: 100%;
          }
        }
        .info {
          width: calc(100% - 120px);
          margin-left: 12px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          .el-button {
            color: #000;
          }
          > .title {
            > div {
              display: flex;
              align-items: center;
              font-size: 14px;
              &.editTitle {
                flex-wrap: wrap;
              }
              .input-new-tag {
                width: 100%;
              }
              .el-icon-edit {
                margin-left: 10px;
              }
            }
          }
          .info-text {
            font-size: 12px;
            span {
              color: #acacac;
            }
          }
          > li {
            .icon-play {
              color: #a1322c;
            }
          }
        }
      }
      .top-btn {
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
.page-wrap {
  float: right;
}
.el-dialog {
  .el-select {
    width: 100%;
  }
}
</style>
